package cn.bgs.servicewebsocket.controller;

import cn.bgs.serviceutils.utils.CSException;
import cn.bgs.serviceutils.utils.R;
import cn.bgs.servicewebsocket.controller.WebSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author:YiChen
 * @program: IntelliJ IDEA
 * @Description:
 * @Created 2021/10/19-9:30
 */
@RestController
@RequestMapping("/WebSocket")
@Slf4j
public class WebSocketController {

    @Autowired
    private WebSocket webSocket;

    @GetMapping("/login/{name}")
    public R login(@PathVariable String name, HttpSession httpSession){
        httpSession.setAttribute("user",name);
        String user = (String) httpSession.getAttribute("user");
        System.out.println(user);
        log.info("登录成功：{}",name);

      return R.ok().message("登陆成功");
    }

    @GetMapping("/getUser")
    public R getUser(){
        return R.ok().data("names",webSocket.getNames());
    }

    @GetMapping("/sendMessage/{toName}/{message}")
    public R sendMessage(@PathVariable String toName, @PathVariable String message){
        try {
            webSocket.sendMessageInfo(toName, message);
        } catch (IOException e) {
            throw new CSException(20001,"消息发送失败");
        }
        return R.ok();
    }
}
